package com.helen.ui.product;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.adapter.ProductAdapter;
import com.helen.entity.ProductEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.DividerGridItemDecoration;
import com.helen.widget.SearchEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by yang on 2018/5/9.
 * 商品
 */

public class ProductActivity extends BaseActivity {
    @BindView(R.id.et_search)
    SearchEditText etSearch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;

    private View errorView;
    private List<ProductEntity> list = new ArrayList();
    private ProductAdapter productAdapter;
    private int page = 1;
    private String name = "";
    private String type = "";

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_product_list;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        String[] homeClassificationName = getResources().getStringArray(R.array.home_classification);
        type = getIntent().getStringExtra("type");
        switch (type) {
            case "1":
                getToolbarTitle().setText(homeClassificationName[9]);
                break;
            case "2":
                getToolbarTitle().setText(homeClassificationName[8]);
                break;
            case "3":
                getToolbarTitle().setText(homeClassificationName[6]);
                break;
        }


        errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) rvList.getParent(), false);
        productAdapter = new ProductAdapter(R.layout.item_product_list, list);
        productAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        swipeRefresh.setRefreshing(true);
        swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.appThemeColor));
        rvList.setLayoutManager(new GridLayoutManager(ProductActivity.this, 2));
        rvList.addItemDecoration(new DividerGridItemDecoration(ProductActivity.this, 6f, R.drawable.shape_recyclerview_divider_decoration_commen));
        rvList.setAdapter(productAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        productAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, rvList);


        productAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ProductEntity productEntity = (ProductEntity) adapter.getData().get(position);
                Intent ti = new Intent(ProductActivity.this, ProductDetailActivity.class);
                ti.putExtra("productId", productEntity.getId());
                startActivity(ti);
            }
        });

        etSearch.setOnSearchClickListener(new SearchEditText.OnSearchClickListener() {
            @Override
            public void onSearchClick(View view) {
                name = etSearch.getText() + "";
                page = 1;
                refresh();
            }
        });

        etSearch.setOnClearClickListener(new SearchEditText.OnClearClickListener() {
            @Override
            public void onClearClick(View view) {
                name = "";
                page = 1;
                refresh();
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                page = 1;
                name = s + "";
            }
        });


        refresh();

    }

    @Override
    protected void updateViews() {

    }


    private void refresh() {
        page = 1;
        productListApi();
    }


    private void loadMore() {
        page++;
        productListApi();
    }

//    商品编号	productid
//    搜索的类型	type       0、所有商品 1、寻找宝贝      2、活动产品 3、大地资源
//    商品名称	name
//    商品类别编号	classid
//    页索引	page
//    页大小	size

    private void productListApi() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("productid", "");
        params.put("type", type + "");
        params.put("name", name);
        params.put("classid", "");
        params.put("page", page + "");
        params.put("size", "10");
        EasyHttp.post(Constants.API_JSONAPI_PRODUCTLIST)
//                .cacheMode(CacheMode.CACHEANDREMOTEDISTINCT)
//                .cacheKey(Constants.API_JSONAPI_PRODUCTLIST + "_" + type)
//                .cacheDiskConverter(new SerializableDiskConverter())
                .params(params)
                .execute(new SimpleCallBack<String>() {
//                .execute(new SimpleCallBack<CacheResult<String>>() {

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                        swipeRefresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(ApiException e) {

                        MyLog.d(TAG, "获取商品列表失败==" + e.toString());
                        MToast.makeTextShort(ProductActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
//                    public void onSuccess(CacheResult<String> stringCacheResult) {
                    public void onSuccess( String stringCacheResult) {
//                        String data = PhoneUtils.checkResponseFlag2(ProductActivity.this, stringCacheResult.data, TAG);
                        String data = PhoneUtils.checkResponseFlag2(ProductActivity.this, stringCacheResult, TAG);
                        if (data != null) {
                            list = new Gson().fromJson(data, new TypeToken<List<ProductEntity>>() {
                            }.getType());
                            if (page == 1) {
                                productAdapter.getData().clear();
                                productAdapter.setNewData(list);
                            } else {
                                productAdapter.addData(list);
                            }
                            if (list.size() < 10) {
                                productAdapter.loadMoreEnd(false);
                                productAdapter.setEmptyView(errorView);
                            } else {
                                productAdapter.loadMoreComplete();
                            }
                        }
                    }
                });

    }


}
